#!/bin/bash

function root_login_time_check() 
{
    SSHD_FILE="/etc/pam.d/sshd"
    #在centOS 8版本以前，使用 pam_tally2.so
    if [ `grep -c "^auth required pam_faillock.so" $SSHD_FILE` -ne "0" ]; then
        echo "sshd pam.d is enhanced."
    else
        #在第二行插入pam配置,“deny=3，unlock_time”表示当普通用户的密码输入错误达到3次后，就锁定用户登录150秒；
        #针对root账户，如果输入密码错误达到3次，锁定300秒。
        sed -i~ '2iauth required pam_faillock.so deny=3 unlock_time=150 even_deny_root root_unlock_time=300' $SSHD_FILE
        echo "the sshd is backuped and enhanced"
    fi
}

function require_password_period_update()
{
    LIGIN_DEFS_FILE="/etc/login.defs"
    PASS_MAX_DAYS=30
    PASS_MIN_DAYS=0
    PASS_MIN_LEN=8
    PASS_WARN_AGE=7

    if [ `grep -c "^PASS_MAX_DAYS   30" $LIGIN_DEFS_FILE` -eq "0" ]; then
        sed -i~ 's/^PASS_MAX_DAYS\t.*/PASS_MAX_DAYS   30/' $LIGIN_DEFS_FILE
        sed -i 's/^PASS_MIN_DAYS\t.*/PASS_MIN_DAYS   0/' $LIGIN_DEFS_FILE
        sed -i 's/^PASS_MIN_LEN\t.*/PASS_MIN_LEN   8/' $LIGIN_DEFS_FILE
        sed -i 's/^PASS_WARN_AGE\t.*/PASS_WARN_AGE   7/' $LIGIN_DEFS_FILE
    else
        echo "$LIGIN_DEFS_FILE is already enhanced"
    fi
}

function config_password_complexity()
{
    PASS_COMPLEXITY_FILE="/etc/security/pwquality.conf"
    if [ `grep -c "^minlen =" $PASS_COMPLEXITY_FILE` -eq "0" ]; then
        echo "minlen = 8" >> $PASS_COMPLEXITY_FILE
        echo "maxrepeat = 2" >> $PASS_COMPLEXITY_FILE
        echo "lcredit = 1" >> $PASS_COMPLEXITY_FILE
        echo "ucredit = 1" >> $PASS_COMPLEXITY_FILE
        echo "dcredit = 1" >> $PASS_COMPLEXITY_FILE
        echo "ocredit = 1" >> $PASS_COMPLEXITY_FILE
    else
        echo "$PASS_COMPLEXITY_FILE is already updated"
    fi

}

function disable_root_login()
{
    SSH_CONFIG_FILE="/etc/ssh/sshd_config"
    #将PermitRootLogin配置为no来禁用root账户通过sshd登录
    if [ `grep -c "^PermitRootLogin no" $SSH_CONFIG_FILE` -eq "0" ]; then
	sed -i~ 's/PermitRootLogin yes/PermitRootLogin no/' $SSH_CONFIG_FILE
	echo "$SSH_CONFIG_FILE is updated"
    else
        echo "$SSH_CONFIG_FILE is already updated"
    fi
}

#main
root_login_time_check
require_password_period_update
config_password_complexity
disable_root_login
